package com.pangzhao.controller;

import com.alibaba.fastjson.JSON;
import com.pangzhao.domain.Order;
import com.pangzhao.domain.Product;
import com.pangzhao.service.OrderService;
import com.pangzhao.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 自定义实现负载均衡
 */
@Slf4j
@RestController
@RequestMapping("/customize")
public class OrderController2 {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 准备买1件商品--下单
     *
     * @param pid
     * @return
     */
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("自定义实现负载均衡>>接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", pid);
        //从nacos中获取服务地址
        //自定义规则实现随机挑选服务
        //调用商品微服务,查询商品信息
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        //随机选择
        int index = new Random().nextInt(instances.size());//0 1 2
        ServiceInstance instance = instances.get(index);
        //获取商品服务ip+端口
        String url = instance.getHost() + ":" +
                instance.getPort();
        log.info(">>从nacos中获取到的微服务地址为:" + url);
        //通过restTemplate调用商品微服务
        Product product = restTemplate.getForObject("http://" + url +
                "/product/" + pid, Product.class);
        log.info(">>商品信息，查询结果:" + JSON.toJSONString(product));
        //下单(创建订单)
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //为了不产生大量的额垃圾数据,暂时不保存订单入库
        // orderService.createOrder(order);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return order;
    }
}
